package com.example.controller;

import com.example.domain.User;
import com.example.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
//处理点赞相关请求
@Controller
public class LikeController {

    @Autowired
    private LikeService likeService;

    // 帖子点赞/取消点赞
    @PostMapping("/like/post")
    @ResponseBody
    public Map<String, Object> togglePostLike(@RequestParam Integer postId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        User user = (User) request.getSession().getAttribute("USER_SESSION");
        if (user == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }

        try {
            likeService.togglePostLike(user.getId(), postId);
            boolean isLiked = likeService.isPostLiked(user.getId(), postId);
            int likeCount = likeService.getPostLikeCount(postId);

            result.put("success", true);
            result.put("isLiked", isLiked);
            result.put("likeCount", likeCount);
            result.put("message", isLiked ? "点赞成功" : "取消点赞");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "操作失败");
        }

        return result;
    }

    // 评论点赞/取消点赞
    @PostMapping("/like/comment")
    @ResponseBody
    public Map<String, Object> toggleCommentLike(@RequestParam Integer commentId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        User user = (User) request.getSession().getAttribute("USER_SESSION");
        if (user == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }

        try {
            likeService.toggleCommentLike(user.getId(), commentId);
            boolean isLiked = likeService.isCommentLiked(user.getId(), commentId);
            int likeCount = likeService.getCommentLikeCount(commentId);

            result.put("success", true);
            result.put("isLiked", isLiked);
            result.put("likeCount", likeCount);
            result.put("message", isLiked ? "点赞成功" : "取消点赞");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "操作失败");
        }

        return result;
    }
}
